// pages/topic/index.js
const {
  topicList,
  zhentiCity,
  attachment
} = require('../../../api/api')
const {
  decodeUserInfo
} = require('../../../api/login')
const selectorRouteDatas = [{
    id: 0,
    title: "地区",
    type: "radiobox",
    key: "province",
    items: []
  },
  {
    id: 1,
    title: "时间",
    key: "year",
    type: 'radiobox',
    items: [{
        id: "2022",
        title: "2022",
        checked: true
      }, {
        id: "2021",
        title: "2021",
      },
      {
        id: "2020",
        title: "2020",
      },
      {
        id: "2019",
        title: "2019",
      },
      {
        id: "2018",
        title: "2018",
      },
      {
        id: "2017",
        title: "2017",
      },
    ],
  },



]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectorDataList: selectorRouteDatas,
    downShow: false,
    selectedData: {
      province: 0,
      year: '2022'
    },
    filterRouteKey: "topicFilters",
    setting: {
      height: '100rpx'
    },
    subjectList: [],
    isVip: false,
    isSvip: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const {
      filterRouteKey,
      selectedData,
    } = this.data
    // selectedData.province = wx.getStorageSync('userCitys').code
    // this.setData({
    //   selectedData
    // })
    // wx.setStorageSync(filterRouteKey, selectedData)
   await this.fetchCity()
    this.getList()
  },
  downTab(e) {
    const {
      i
    } = e.currentTarget.dataset
    const {
      subjectList
    } = this.data
    subjectList[i].status = !subjectList[i].status
    this.setData({
      subjectList
    })
  },
  async getList() {
    const {
      selectedData
    } = this.data
    const params = {
      province: selectedData.province,
      year: selectedData.year
    }
    const {
      result
    } = await topicList(params)
    result.map(e => {
      e.status = true
    })
    this.setData({
      subjectList: result
    })
  },
  previewDocument: async function (e) {
    var {
      current,
      type,
      pid
    } = e.currentTarget.dataset
    const params = {
      type,
      pid
    }
    const {
      isVip,
      isSvip
    } = this.data
    if (type == 2 && !isSvip) {
      wx.navigateTo({
        url: '/pages/article/vip/index',
      })
      return
    }
    if (!isVip) {
      wx.navigateTo({
        url: '/pages/article/vip/index',
      })
      return
    }
    const {
      result
    } = await attachment(params)
    if (result.length == 1) {
      wx.showLoading({
        title: '正在加载文件...',
        mask: true
      })
      wx.downloadFile({
        url: result[0].link,
        success: function (res) {
          // console.log(res)
          wx.hideLoading()
          const tempFilePath = res.tempFilePath;
          wx.openDocument({
            filePath: tempFilePath,
            success: function (res) {
              // console.log('打开文档成功')
            },
          });

        },
        fail() {
          wx.hideLoading()
        }
      });
      return
    }
    let title = type == 1 ? '试题' : '答案'
    wx.navigateTo({
      url: '/pages/article/list/index?mode=' + 'zhenti' + '&title=' + title + (result.length > 0 ? '&list=' + JSON.stringify(result) : '')
    })

  },
  async fetchCity() {
    const {
      selectorDataList,
      selectedData,
      filterRouteKey
    } = this.data
    const cityName = wx.getStorageSync('userCitys').name
    const {
      result
    } = await zhentiCity()
    const cityList = result.map(e => {
      return {
        id: e.province,
        title: e.province,
        // yearList:e.yearList.map(e=>{return {id:e,title:e}})
      }
    })
    // const {
    //   yearList
    // } = result[0]
    var newList = cityList.filter((item) => {
      return item.id == cityName
    })
    let yearList=[]
  result.filter((item) => {
    if(item.province == cityName){
      yearList=item.yearList
    }
    })
    selectedData.province = newList.length > 0 ? newList[0].id : cityList[0].id
    selectedData.year = yearList[0]

    this.setData({
      selectedData
    })
    wx.setStorageSync(filterRouteKey, selectedData)
    // const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    // console.log(cityList)
    selectorDataList[0].items = cityList
    selectorDataList[1].items = yearList.map(e => {
      return {
        id: e,
        title: e
      }
    })
    this.setData({
      selectorDataList,
      data: result
    })
    this.filterKeyFunc()
  },
  filterKeyFunc() {
    const {
      filterRouteKey,
      data
    } = this.data
    const selectedData = wx.getStorageSync(filterRouteKey)
    const {
      selectorDataList
    } = this.data
    var list = []
    data.map((item) => {
      if (item.province == selectedData['province']) {
        list = item.yearList.map(e => {
          return {
            id: e,
            title: e
          }
        })
        if (selectedData['province'] !== this.data.selectedData['province']) {
          selectedData['year'] = list[0].id
          selectorDataList[1].items = list
          wx.setStorageSync(filterRouteKey, selectedData)
        }
      }
    })
    selectorDataList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      item.title = c.length > 0 ? c[0].title : item.title
    })
    this.setData({
      selectorDataList,
      selectedData
    })
    this.getList()
  },
  async onSelectChangedRoute(e) {
    const {
      filterRouteKey
    } = this.data
    wx.setStorageSync(filterRouteKey, {
      ...e.detail
    });
    this.filterKeyFunc()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  onShow() {
    this.fetchUserInfo()
  },
  async fetchUserInfo() {
    const {
      vipType
    } = await getApp().fetchUserInfo()
    this.setData({
      isVip: vipType,
      isSvip: vipType == 'svip' ? vipType : false,
      typeVip: vipType == 'vip' ? 'svip' : 'vip'
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '德道升学',
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  }
})